<template>
    <div class="loan-out-share" v-if='pageLoaded'>
        <!-- wrapper -->
        <div class="wrapper">
            <img src="../images/sharelanding_head.jpg" width="100%">
            <div class="loan-detail-header" v-if='userInfo.user'>
                <div class="loan-detail-user">
                    <span class="loan-detail-user__avatar"><img :src="userInfo.user.avatar || placeholderImg" alt=""></span>
                    <div class="loan-detail-user__info">
                        <p class='name'>{{userInfo.user.realName}}</p>
                        <p>出借人</p>
                    </div>
                    <span class="button short transparent" @click='goReportDetail'>信用报告</span>
                </div>
            </div>
            <div class="loan-out-card card">
                <p class="loan-number">编号: {{number}}</p>
                <div class="card__header no-border">
                    <div class="loan-money">
                        <p class="loan-money__info loan-out">可借额度</p>
                    </div>
                    <div class="fundraising-info">
                        <p class="loan-money__amount purple">{{detail.lendAmountFrom | toYuan}}～{{detail.lendAmountTo | toYuan}}元</p>
                    </div>
                </div>
                <ul class="loan-out-info">
                    <li class="loan-out-info__item" v-if='detail.daysType == "DAY"'>
                        <p>{{daysTransform(detail.lendDaysFrom,detail.lendDaysTo,'day')}}</p>
                        <span>可借时长</span>
                    </li>
                    <li class="loan-out-info__item" v-else>
                        <p>{{daysTransform(detail.lendDaysFrom,detail.lendDaysTo,'period')}}</p>
                        <span>可借时长</span>
                    </li>
                    <li class="loan-out-info__item">
                        <p>{{detail.yearRate / 100}}%</p>
                        <span>年利率</span>
                    </li>
                    <li class="loan-out-info__item">
                        <p>{{detail.serviceFeeRate / 100}}% | {{detail.serviceFee | toYuan}}元</p>
                        <span>服务费</span>
                    </li>
                </ul>
                <ul class="card__info">
                    <li class="card__info-item">发布日期：{{ detail.createdAt | dateFormat }}</li>
                    <li class="card__info-item">还款方式：{{ detail.repayWayStr }}</li>
                </ul>
                <!-- <p class="card__info-item">必备信用资料：{{ detail.myCreditMaterialInfo || placeholder }}</p> -->
                <!-- <p class="card__info-item full">补充说明：{{ detail.addSay || placeholder }}</p> -->
                <!-- <p class="card__info-item full">
                    <span class='orange'>{{detail.applyCount}}</span>
                    人申请  |  {{ caclPersent(detail.passCount, detail.rejectCount) }}%通过  |  {{detail.dealAvgTime | timeToHours}}小时处理<br>  最近成交:{{detail.recentSuccessDate | dateFormat}}</p> -->
                <p class="card__info-item full">
                    <span class='orange'>{{detail.applyCount}}</span>
                    人申请   |  {{detail.dealAvgTime | timeToHours}}小时处理</p>
            </div>


            
        </div>
            
        <!-- footer -->

        <footer class="single-button" v-if='!detail.isMyPublishLend'>
            <span class="button" @click='goLoanInApply'>马上申请</span>
        </footer>

        <confirm 
            :show='show_modal_close_loan_out'
            @close='show_modal_close_loan_out = false'
            @confirm='closeLoanOut'
            title='确认关闭出借'
            tips='是否确认关闭出借'></confirm>

        <confirm 
            :show='show_modal_open_loan_out'
            @close='show_modal_open_loan_out = false'
            @confirm='openLoanOut'
            title='确认重新发布出借'
            tips='是否确认重新发布出借'></confirm>

        <modal
            :show='show_modal_qr'
            @close='show_modal_qr = false'
            transparent>
            <div class="modal-qr">
                <img src="../images/qr.png" width="240">
            </div>
        </modal>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import confirm from '../components/Confirm.vue'
    import modal from '../components/Modal.vue'
    import toYuan from '../filters/filter-toYuan'
    import dateFormat from '../filters/filter-dateFormat'
    import { timeToHours } from '../filters/filter-timeFormat'
    import  { mapGetters, mapActions }  from 'vuex'
    import { loanOutApi, contactApi } from '../api/api'
    import moment from 'moment'

    export default {
        components:{
            confirm,
            modal
        },
        filters:{
            toYuan,
            dateFormat,
            timeToHours
        },
        data() {
            return {
                placeholderImg:require('../images/loading_1.png'),
                number:this.$route.params.number,
                pageLoaded:false,
                isMyPublishLend:false,
                detail:{},
                userInfo:{},
                show_modal_close_loan_out:false,
                show_modal_open_loan_out:false,
                show_modal_loan_detail:false,
                show_modal_qr:false,
                argeement:true,
                payway:-1,
                payPasswordShow:false,
                payStatus:'',
                password:'',
                placeholder:'--',
                userCount:'',
                listInfo:{},
                records:[],
                loading:true,
                loading_count:true,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            currentPage(){
                if(_.isEmpty(this.listInfo)) return 1
                return this.listInfo.pageNum
            },
            storeUserInfo(){
                return this.localInfo.userInfo
            },
            needLogin(){
                return this.localInfo.needLogin
            },
            hasUserCount(){
                return !_.isEmpty(this.userCount)
            },
            noEditObject(){
                return _.isEmpty(this.editObject)
            },
            noInvoiceInfo(){
                return _.isEmpty(this.invoiceInfo)
            }
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'removeLoanInForm',
                'setShare',
                'setGoHome'
            ]),


            goReportDetail(){
                if(!this.userInfo.creditReport){
                    this.setMsgTip({
                        text:'该用户暂无信用报告！',
                        type:'warn'
                    })
                    return
                }
                this.$router.push({
                    name:'user-credit-report-detail',
                    params:{
                        no:this.userInfo.creditReport.creditReportNo
                    }
                })
            },
            share(item){
                let protocol = location.protocol
                let host = location.host
                let pathname = location.pathname
                let search = location.search

                let realUrl = `${protocol}//${host}${pathname}${search}#share-loan-out/${item.lendNo}`
                let days

                if(item.daysType == 'DAY'){
                    days = this.daysTransform(item.lendDaysFrom,item.lendDaysTo,'day')
                }
                else{
                    days = this.daysTransform(item.lendDaysFrom,item.lendDaysTo,'period')
                }
                this.setShare({
                    message:{
                        title: '安牛有借，海量客户，一键拓客 ', // 分享标题
                        desc: `金额: ${toYuan(item.lendAmountFrom)}-${toYuan(item.lendAmountTo)},时长: ${days}, 利率: ${(item.yearRate / 100).toFixed(2)}%`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () { 

                        },
                        cancel: function () { 

                        }
                    },
                    timeline:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                    qq:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        desc: `金额: ${toYuan(item.lendAmountFrom)}-${toYuan(item.lendAmountTo)},时长: ${days}, 利率: ${(item.yearRate / 100).toFixed(2)}%`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                })
            },
            daysTransform(from,to,type){
                let suffix
                let fromStr = from
                let toStr = to

                if(type == 'day') suffix = '天'
                else suffix = '期'

                if(from >= 30 && type == 'day'){
                    suffix = '个月'
                    fromStr = from / 30 
                    toStr = to / 30 

                }
                if(from == to){
                    return fromStr + suffix
                }
                else{
                    return fromStr + suffix + '~' + toStr + suffix
                }
            },
            caclPersent(pass,reject){
                if(pass == 0) return 0
                return (pass/(pass+reject)*100).toFixed(2)
            },
            rate(data1,data2){
                if(data1 == 0){
                    return '0%'
                }
                return  100 * (data1 / data2).toFixed(2) + '%'
            },
            goApply(){
                this.$router.push({
                    name:'loan-out-apply'
                })
            },
            goLoanInApply(){
                // if(!this.storeUserInfo.isFocus){
                //     this.show_modal_qr = true
                //     return
                // }
                if(!this.needLogin){
                    if(this.storeUserInfo.user){
                        this.$router.push({
                            name:'loan-out-detail-other',
                            params:{
                                number:this.number
                            }
                        })
                    }
                }
                else{
                    if(this.userInfo.user){
                        this.$router.push({
                            name:'bind-phone',
                            query:{
                                mobile:this.userInfo.user.mobile,
                                number:this.number,
                                loan:'out'
                            }
                        })
                    }
                }

            },
            goLoanInDetailOther(number){
                this.$router.push({
                    name:'loan-in-detail-other',
                    params:{
                        number:number
                    }
                })
            },
            goSuccess(){
                this.$router.push({
                    name:'loan-in-success'
                })
            },
            closeLoanOut(){
                this.showLoading()
                loanOutApi.close({
                    lendNo:this.number
                })
                .then(result=>{
                    this.hideLoading()
                    history.go(-1)
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            openLoanOut(){
                this.showLoading()
                loanOutApi.open({
                    lendNo:this.number
                })
                .then(result=>{
                    this.hideLoading()
                    history.go(-1)
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            goPay(){
                this.payStatus = true
                console.log(1)
            },
            goDetail(item){
                this.$router.push({
                    name:'user-detail',
                    params:{
                        id:item.userId,
                    }
                })
            },
            getDetail(){
                return loanOutApi.detailOther({
                    lendNo:this.number
                })
                .then(result=>{
                    this.detail = result
                    this.share(result)
                })
            },
            getUserInfo(){
                return loanOutApi.userInfo({
                    lendNo:this.number
                })
                .then(result=>{
                    this.userInfo = result
                })
            },
        },
        created(){

            this.showLoading()
            Promise.all([this.getUserInfo(this.number), this.getDetail()])
            .then(result=> {
                this.pageLoaded = true
                this.hideLoading()
            })
            .catch(error=> {
                console.error(error);
                this.pageLoaded = true
                this.hideLoading()
            });
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-out-share{
        .loan-out-target{
            background-color: #fff;
            padding:0 25px 0 16px;
        }
        .target__info{
            overflow: hidden;
            position: relative;
            padding-bottom: 16px;
            padding-top: 16px;
            border-bottom:1px solid $sectionColor;
        }
        .target__info-item{
            margin-left:-1px;
            border-left:1px solid $sectionColor;
            width: 50%;
            float:left;
            padding: 4px 0;
            box-sizing:border-box;
            display: flex;
            align-items: center;
            justify-content: space-between;
            &:nth-child(odd){
                padding-right:16.5px;
            }
            &:nth-child(even){
                padding-left:16.5px;
            }
            @extend %font-body1;
            span{
                display: block;
                position: relative;
                padding-left: 22px;
                &:before{
                    content:'';
                    position: absolute;
                    left:0;
                    top:50%;
                    margin-top:-6px;
                    width: 12px;
                    height: 12px;
                }
                &.view:before{ background-color: #9CCC65 }
                &.apply:before{ background-color: #00BFA5 }
                &.pass:before{ background-color: #5C6BC0 }
                &.no-pass:before{ background-color: #FF6E40 }
                &.apply-rate:before{ background:linear-gradient(-45deg, #00BFA5 50%, #9CCC65 0) }
                &.pass-rate:before{ background:linear-gradient(-45deg, #FF6E40 50%, #5C6BC0 0) }
            }
            p{
                color:$importColor;
                text-align:right;
            }
            .logo{
                width: 32px;
                height: 32px;
                display: block;
                img{
                    width: 100%;
                    height: 100%;
                }
            }
        }
        .loan-out-card{
            padding-top: 0;
            margin:0;
            box-shadow:none;
        }
        .wrapper{
            padding-bottom: 100px;
        }
        .apply-record{
            background-color: #fff;
        }
        .apply__people{
            @extend %font-body1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding:12px 16px;
        }
        .apply__info{
            display: flex;
            flex:1;
            align-items: center;
            color:$importColor;
            @extend %font-body1;
            img{
                width: 40px;
                height: 40px;
                border-radius:50%;
                border:1px solid $sectionColor;
                box-sizing: border-box;
            }
            p{
                padding: 0 10px 0 10px;
            }
            span{
                display: block;
                padding-right: 10px;
            }
        }
        .apply__status{
            width: 3em;
            color:$importColor;
            &.wait{
                color:$purple;
            }
        }
    }

</style>
